package com.yylending.las.lending.quota.uploadimg;

import android.text.TextUtils;

import com.yyfax.common.CLog;
import com.yyfax.infrastructure.Constants;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by laixj on 2016/11/17.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class UploadImgPresenter extends Presenter<UploadImgModel, UploadImgPresenter.View> {
	public static final String TAG = "UploadImgPresenter";

	public interface View extends IView {
		void onUploadImageSuccess(String filePath, String fileName, String imageId);

		void onUploadImageFailure(String filePath, String tips);

		void onUploadImageCancel(String filePath, String tips);
	}

	public static class Generator implements PresenterFactory<UploadImgPresenter> {
		@Override
		public UploadImgPresenter create() {
			return new UploadImgPresenter();
		}
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new UploadImgModel();
		EventAgent.register(this);
		CLog.i(TAG, "UploadImgPresenter attach=" + (mView == null ? "" : mView.toString()));
		CLog.i(TAG, "UploadImgPresenter attach mRequestPage=" + mRequestPage);
	}

	@Override
	public void detach() {
		CLog.i(TAG, "UploadImgPresenter detach=" + (mView == null ? "" : mView.toString()));
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public void uploadFileByBytes(final byte[] bytes, final String filename, final String imageType) {
		if (bytes == null) {
			mView.onUploadImageFailure(filename, "图片上传失败!");
			CLog.i(TAG, "图片为空");
			return;
		}

		final RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), bytes);
		MultipartBody.Part part = MultipartBody.Part.createFormData("files", filename, requestBody);
		RequestBody type = RequestBody.create(MediaType.parse("text/plain"), imageType);
		UploadImgModel.UploadImage entity = new UploadImgModel.UploadImage(part, type);

		CLog.i(TAG, "上传图片-->" + filename);
		if (!Constants.isConnected) {//如果没有网络
			UploadImgModel.UploadFailure result = new UploadImgModel.UploadFailure();
			result.filePath = filename;
			result.requestPage = mRequestPage;
			result.tips = "连接网络失败，请检查网络设置";
			EventAgent.post(result);
			return;
		}
		//noinspection unchecked
		mModel.execute(entity, FUNCTIONAL_CODE, filename, mRequestPage)
				.compose(mBaseView.composeLifecycle())//销毁Presenter前停止上传
				.subscribe(new Subscriber<BaseResultEntity>() {
					private boolean success = false;

					@Override
					public void onStart() {
						CLog.d(TAG, "new Subscriber: onStart");
					}

					@Override
					public void onNext(final BaseResultEntity result) {
						success = true;
						CLog.d(TAG, "new Subscriber: onNext filename=" + filename);
						result.extraParam = filename;
						result.requestPage = mRequestPage;
						EventAgent.post(result);
					}

					@Override
					public void onCompleted() {
						CLog.d(TAG, "new Subscriber: onCompleted filename=" + filename);
						CLog.d(TAG, "new Subscriber: onCompleted success=" + success);
						if (!success) {
							UploadImgModel.UploadCancel result = new UploadImgModel.UploadCancel();
							result.filePath = filename;
							result.requestPage = mRequestPage;
							result.tips = "图片上传失败";
							EventAgent.post(result);
						}
						unsubscribe();
					}

					@Override
					public void onError(Throwable e) {
						CLog.d(TAG, "new Subscriber: onError");
						UploadImgModel.UploadFailure result = new UploadImgModel.UploadFailure();
						result.filePath = filename;
						result.requestPage = mRequestPage;
						result.tips = "图片上传失败";
						EventAgent.post(result);
						unsubscribe();
					}
				});
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadResult(UploadImgModel.UploadResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "UploadImgPresenter uploadResult=" + (mView == null ? "" : mView.toString()));
			String filePath = (String) result.extraParam;
			CLog.i(TAG, "上传图片返回fileName=" + filePath);
			if (BaseResultEntity.isResponseSuccess(result) && null != result.getData()) {
				CLog.i(TAG, "上传图片返回=" + result.toString());
				Map<String, String> uploadResult = result.getData();
				/*if (Global.IMG_ID_CARD_HEAD.equals(type)) {
					result.idCardHead = rs.get(Global.AVATAR_NAME).getAsString();
				} else if (Global.IMG_ID_CARD_FRONT.equals(type)) {
					result.idCardFront = rs.get(Global.POSITIVE_NAME).getAsString();
				} else if (Global.IMG_ID_CARD_BACK.equals(type)) {
					result.idCardBack = rs.get(Global.NEGATIVE_NAME).getAsString();
				} else if (Global.IMG_FACE_RECOGNIZE.equals(type)) {
					if (Global.FACE_NAME_QUOTA.equals(filename)) {
						result.faceRecognize = rs.get(Global.FACE_NAME_QUOTA).getAsString();
					} else if (Global.FACE_NAME_WITHDRAW.equals(filename)) {
						result.faceRecognize = rs.get(Global.FACE_NAME_WITHDRAW).getAsString();
					}
				}*/
				mView.onUploadImageSuccess(filePath, filePath, uploadResult.get(filePath));
			} else {
				String msg = TextUtils.isEmpty(result.getRetMsg()) ? "图片上传失败!" : result.getRetMsg();
				mView.onUploadImageFailure(filePath, msg);
			}
		} else {
			CLog.i(TAG, "UploadImgPresenter mRequestPage=" + mRequestPage);
			CLog.i(TAG, "UploadImgPresenter result.requestPage=" + result.requestPage);
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadFailure(UploadImgModel.UploadFailure result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "UploadImgPresenter uploadFailure=" + (mView == null ? "" : mView.toString()));
			String filePath = result.filePath;
			CLog.i(TAG, "上传图片返回filePath=" + filePath);
			mView.onUploadImageFailure(filePath, result.tips);
		} else {
			CLog.i(TAG, "UploadImgPresenter uploadFailure=" + mRequestPage);
			CLog.i(TAG, "UploadImgPresenter uploadFailure.requestPage=" + result.requestPage);
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void uploadCancel(UploadImgModel.UploadCancel result) {
		if (mRequestPage.equals(result.requestPage)) {
			CLog.i(TAG, "UploadImgPresenter uploadCancel=" + (mView == null ? "" : mView.toString()));
			String filePath = result.filePath;
			CLog.i(TAG, "上传图片返回filePath=" + filePath);
			mView.onUploadImageCancel(filePath, result.tips);
		} else {
			CLog.i(TAG, "UploadImgPresenter uploadCancel=" + mRequestPage);
			CLog.i(TAG, "UploadImgPresenter uploadCancel.requestPage=" + result.requestPage);
		}
	}
}
